const App = getApp();
const func = require('../../utils/func');
const util = require('../../utils/util.js');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        // 购物车参数
        page: 1,
        total: 0,
        perPage: 0,
        lastPage: 1,
        currentPage: 1,
        isLoading: true,
        loadCart: false,
        nullCart: false,
        shopCart: {},
        // 正常商品操作按钮
        shopCartAction: [
            {name: '删除', color: '#fff', fontsize: 28, width: 64, background: '#F82400'},
            {name: '收藏', color: '#fff', fontsize: 28, width: 64, background: '#FFC600'}
        ],
        // 异常商品(失效商品)
        abnormalGoods: {},
        // 失效商品操作按钮
        abnormalAction: [
            {name: '删除', color: '#fff', fontsize: 28, width: 64, background: '#F82400'}
        ],
        // apiArclist商品
        recomGoods: {},
        // 选中商品总价、选中商品数、是否全选
        cartGlobal: {},
        // 登录参数
        Login: false,
        isLogin: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let _this = this,
        
		obj = wx.getMenuButtonBoundingClientRect();
        _this.setData({
			width: obj.left,
			height:( obj.top + obj.height + 12 ) * 2,
			inputTop: obj.top + (obj.height - 30) / 2,
			arrowTop: obj.top + (obj.height - 32) / 2,
		}, () => {
			wx.getSystemInfo({
				success: (res) => {
					_this.setData({
						statusBarHeight:res.statusBarHeight,
					    scrollH: res.screenHeight,
						//略小，避免误差带来的影响
						dropScreenH: _this.data.height * 750 / res.windowWidth +
							86,
						drawerH: res.windowHeight - res.windowWidth / 750 *
							100 - _this.data.height
					})
				}
			})
		});
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let _this = this;
        if (App.checkIsLogin() == true) {
            _this.getCartList();
            _this.setData({
                isLogin: App.checkIsLogin(),
            })
        } else{
            _this.setData({
                isLogin: App.checkIsLogin(),
                isLoading: false,
            })
        }
    
    },

    // 下拉刷新
    onPullDownRefresh() {
        let _this = this;
        _this.data.page = 1;
        _this.data.lastPage = 1;
        _this.setData({page: _this.data.page, lastPage: _this.data.lastPage});
        // 获取订单列表
        _this.getCartList();
        wx.stopPullDownRefresh();
    },

    // 上拉加载
    onReachBottom() {
        let _this = this;
        if (_this.data.perPage >= _this.data.total) return false;
        _this.setData({loadCart: true});
        if (_this.data.page >= _this.data.lastPage) {
            _this.setData({page: _this.data.page, nullCart: true, loadCart: false, isLoading: false});
            return false;
        }
        _this.getCartList(true, ++_this.data.page);
    },

    /**
     * 获取购物车列表
     */
    getCartList(isPage, page) {
        let _this = this;
        let postData = {
            page: page || 1,
            apiArclist_1: `ekey=1&channel=2&limit=6&label=1`,
        };
        App._requestApi(_this, App.globalData.config.shopCartListUrl, postData, function (res) {
            if (res.data.cart_total_num > 0) {
				wx.setTabBarBadge({
					index: 2,
					text: String(res.data.cart_total_num )
				});
			} else if(res.data.cart_total_num == 0){
			  wx.removeTabBarBadge({
			        index: 2
			    });
			}
            // 显示页面
            _this.setData({nullCart: false, loadCart: false, isLoading: false});
            let resCart = res.data.shopCart.data;   
            let recomGoods = res.data.apiArclist[1]; // 第一个list文档列表数据
            let abnormalGoods = res.data.abnormalGoods;
            if (isPage == true) {
                if (resCart.length == 0) {
                    _this.setData({nullCart: true});
                } else {
                    let shopCart = _this.data.shopCart;
                    _this.setData({
                        abnormalGoods: abnormalGoods,
                        shopCart: shopCart.concat(resCart),
                        lastPage: res.data.shopCart.last_page,
                    });
                }
            } else {
                _this.setData({
                    shopCart: resCart,
                    recomGoods: recomGoods,
                    abnormalGoods: abnormalGoods,
                    total: res.data.shopCart.total,
                    cartGlobal: res.data.cartGlobal,
                    perPage: res.data.shopCart.per_page,
                    lastPage: res.data.shopCart.last_page,
                });
            }
        });
    },

    // 购物车商品数量操作
    shopCartGoodsNumber: function (e) {
        let _this = this;
        let product_num = e.detail.value;
        let cart_id = e.currentTarget.dataset.id;
        let postData = {
            action: 'number',
            cart_id: cart_id,
            product_num: product_num,
        };
        App._requestApi(_this, App.globalData.config.shopCartActionUrl, postData,
            function (res) {
                _this.getCartList();
            }
        );
    },

    // 单个选中\取消
    selectedFind(e) {
        let _this = this;
        let cart_ids = e.detail.value;
        let postData = {
            action: 'selected',
            cart_ids: cart_ids,
        };
        App._requestApi(_this, App.globalData.config.shopCartActionUrl, postData,
            function (res) {
                _this.getCartList();
            }
        );
    },

    // 选择框全选\取消
    selectedAll(e) {
        let _this = this;
        let isChecked = e.detail.value[0];
        let postData = {
            action: 'selectedAll',
            selectedAll: parseInt(isChecked) === 1 ? 1 : 0
        };
        App._requestApi(_this, App.globalData.config.shopCartActionUrl, postData,
            function (res) {
                _this.getCartList();
            }
        );
    },

    // 删除购物车选中商品
    delShopCartCheckedGoods() {
        let _this = this;
        wx.showModal({
            title: '提示',
            content: '确定要删除选中商品吗？',
            success (o) {
                if (o.confirm) {
                    _this.setData({isLoading: true});
                    let postData = {
                        checked: 1,
                        cart_id: 0,
                        action: 'delCart',
                    };
                    App._requestApi(_this, App.globalData.config.shopCartActionUrl, postData,
                        function(res) {
                            App.showSuccess(res.msg, function() {
                                _this.setData({shopCart: {}});
                                _this.getCartList();
                            });
                        },
                        function(res) {
                            App.showError(res.msg);
                        }
                    );
                }
            }
        })
    },

    // 清空失效商品
    delAllAbnormalGoods() {
        let _this = this;
        wx.showModal({
            title: '提示',
            content: '确定要清空失效商品吗？',
            success (o) {
                if (o.confirm) {
                    let postData = {
                        action: 'abnormal',
                    };
                    App._requestApi(_this, App.globalData.config.shopCartActionUrl, postData,
                        function(res) {
                            App.showSuccess(res.msg, function() {
                                _this.getCartList();
                            });
                        },
                        function(res) {
                            App.showError(res.msg);
                        }
                    );
                }
            }
        })
    },

    // 删除购物车单个商品( ey-swipe-action 组件调用 )
    delShopCartFindGoods(cartID) {
        let _this = this;
        wx.showModal({
            title: '提示',
            content: '确定要删除这个商品吗？',
            success (o) {
                if (o.confirm) {
                    let postData = {
                        checked: 0,
                        action: 'delCart',
                        cart_id: cartID,
                    };
                    App._requestApi(_this, App.globalData.config.shopCartActionUrl, postData,
                        function(res) {
                            App.showSuccess(res.msg, function() {
                                _this.setData({isLoading: true});
                                _this.getCartList();
                            });
                        },
                        function(res) {
                            App.showError(res.msg);
                        }
                    );
                }
            }
        })
    },

    // 收藏购物车商品( ey-swipe-action 组件调用 )
    collectShopCartFindGoods(cartID) {
        let _this = this;
        let shopCart = _this.data.shopCart;
        let cartData = shopCart.find((val) => {
                return val.cart_id == cartID;
            });
        let postData = {
            source: 'shopCart',
            aid: cartData.product_id ? cartData.product_id : 0,
        };
        App._requestApi(_this, App.globalData.config.apiGetCollectUrl, postData,
            function(res) {
                App.showSuccess(res.msg);
            },
            function(res) {
                App.showError(res.msg);
            }
        );
    },

    // 购物车结算
    submitShopCartGoods() {
        let _this = this;
        if (parseFloat(_this.data.cartGlobal.cartTotalPrice) !== NaN && parseFloat(_this.data.cartGlobal.cartTotalPrice) > 0) {
            wx.navigateTo({url: '/pages/submitOrder/submitOrder?cartSubmit=1'});
        } else {
            App.showError("请选择购买商品");
        }
    },

    // 跳转到其他界面
    jumpToView(e) {
        func.jumpToUrl(e)
    },

    // /**
    //  * 授权登录
    //  */
    // getUserInfo(e) {
    //     let _this = this;
    //     App.getUserInfo(e, () => {
    //         // 跳转回原页面
    //         wx.reLaunch({
    //             url: '/pages/flow/index',
    //         })
    //     });
    // },

    // 展示弹窗
    showLogin() {
        App.doLogin()
    },
})